package org.example.infrastructure.repository.orm.messageQueue.producer;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.infrastructure.repository.orm.messageQueue.constant.UrlShortenerCoreMQConstant;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class UrlShortenerCoreStatsSaveProducer {
    private final RocketMQTemplate rocketMQTemplate;

    public void send(Map<String, String> producerMap){
        String keys = UUID.randomUUID().toString();
        producerMap.put(MessageConst.PROPERTY_KEYS, keys);
        Message<Map<String, String>> build = MessageBuilder
                .withPayload(producerMap)
                .setHeader(MessageConst.PROPERTY_KEYS, keys)
                .build();
        SendResult resultResult;

        try {
            resultResult = rocketMQTemplate.syncSend(UrlShortenerCoreMQConstant.STATA_SAVE_TOPIC, build);
            log.info("[消息访问统计监控] 消息发送结果: {}, 消息Id:{}, 消息keys:{}", resultResult.getSendStatus(), resultResult.getMsgId(), keys);
        } catch (Exception e) {
            log.error("[消息访问统计监控] 消息发送失败, 消息体:{} \n", JSON.toJSONString(producerMap), e);
        }

    }


}
